package com.ladybug.flow.common.security.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ladybug.flow.common.exception.customexceptions.ServiceException;
import com.ladybug.flow.modules.system.domain.entitys.SysUser;
import com.ladybug.flow.modules.system.mapper.SysUserMapper;
import com.ladybug.flow.common.exception.enums.ErrorEnum;
import com.ladybug.flow.common.security.dto.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @description: 用户数据获取实现
* @author long
* @date 2022/10/14 14:50
* @version 1.0
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService, UserDetailsPasswordService {
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userAccount) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserAccount,userAccount);
        SysUser user = userMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new ServiceException(ErrorEnum.USER_NAME_OR_PWD_ERROR);
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中

        //封装成UserDetails对象返回
        return new LoginUserDTO(user);
    }

    @Override
    public UserDetails updatePassword(UserDetails userDetails, String s) {
        LoginUserDTO loginUserDTO = (LoginUserDTO) userDetails;
        SysUser user = loginUserDTO.getUser();
        user.setPassword(s);
        userMapper.updateById(user);
        loginUserDTO.setUser(user);
        return loginUserDTO;
    }
}
